package com.wuzao.SingletonPattern.first.hacker;

import com.wuzao.SingletonPattern.first.implway.HungrySingleton;

import java.lang.reflect.Constructor;

/**
 * 本包中的示例就是展示对于普通单例实现的安全性问题
 *
 * 利用反射可以越过普通单例类的唯一限制
 * 下面的例子就是使用反射创建单例类的第二个实例
 */
public class ReflectionSingletonTest {

    public static void main(String[] args) {

        HungrySingleton instanceOne = HungrySingleton.getInstance();
        HungrySingleton instanceTwo = null;
        try {
            Constructor<?>[] constructors = HungrySingleton.class.getDeclaredConstructors();
            for (Constructor<?> constructor : constructors) {
                //Below code will destroy the singleton pattern
                constructor.setAccessible(true);
                instanceTwo = (HungrySingleton) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(instanceOne.hashCode());
        assert instanceTwo != null;
        System.out.println(instanceTwo.hashCode());


    }

}
